<template>
  <div>
    <div class="suite-form">
      <el-card>
        <!-- 面包屑 -->
        <div>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/index' }"
              >首页</el-breadcrumb-item
            >
            <el-breadcrumb-item>测试套件</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <br />

        <!-- 查询 -->
        <el-form
          :inline="true"
          :model="queryForm"
          label-width="80px"
          class="search-form"
          size="small"
        >
          <el-form-item label="套件名称">
            <el-input
              v-model="queryForm.name"
              placeholder="请输入套件名称"
              clearable
            >
            </el-input>
          </el-form-item>

          <!-- <el-form-item label="运行模式">
            <el-select
              v-model="queryForm.mode"
              placeholder="请选择运行模式"
              clearable
            >
              <el-option
                v-for="item in runMode"
                :key="item.lable"
                :label="item.lable"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item>
            <el-button type="primary" @click="loadSuite">查询</el-button>
            <el-button type="success" @click="handleAddSuite">新增</el-button>
          </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table
          border=""
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          size="medium"
        >
          <el-table-column label="ID" prop="id" width="50"></el-table-column>
          <el-table-column
            label="套件名称"
            width="300"
            show-overflow-tooltip
            prop="name"
          >
            <template slot-scope="scope">
              <el-tag effect="plain">
                {{ scope.row.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="套件描述" prop="desc"> </el-table-column>
          <el-table-column label="运行模式" width="120"> 同步 </el-table-column>
          <el-table-column label="执行次数" width="120" prop="count">
          </el-table-column>

          <el-table-column
            label="最近执行结果"
            show-overflow-tooltip
            width="120"
            prop="result"
          >
            <template slot-scope="scope">
              <el-tag
                :type="
                  scope.row.result == 1
                    ? 'success'
                    : scope.row.result == 0
                    ? 'danger'
                    : 'primary'
                "
              >
                {{
                  scope.row.result == 1
                    ? "成功"
                    : scope.row.result == 0
                    ? "失败"
                    : "未知"
                }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="创建人" width="100" prop="creator">
            <template slot-scope="scope">
              <el-tag type="primary" effect="plain" size="medium">
                {{ scope.row.creator }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="更新人" width="100" prop="updator">
            <template slot-scope="scope">
              <el-tag type="primary" effect="plain" size="medium">
                {{ scope.row.updator }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
            label="更新时间"
            width="160"
            prop="update_time"
            :formatter="dateFormat"
          >
          </el-table-column>

          <!-- 操作按钮 -->
          <el-table-column label="操作" width="320" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="editData(scope.$index, scope.row)"
                type="primary"
                >编辑
              </el-button>
              <el-button
                size="mini"
                @click="runSuit(scope.$index, scope.row)"
                type="success"
                plain
                >运行
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row.id)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <br />

        <!-- 分页 -->
        <div>
          <el-pagination
            background
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            :page-sizes="[12, 20, 50, 100]"
            :total="pagination.total"
            :current-page.sync="pagination.page"
            @current-change="loadSuite(pagination.page)"
          >
          </el-pagination>
        </div>
      </el-card>
    </div>

    <!-- // 新增套件弹窗表单 -->
    <el-dialog
      :dialogTitle="dialogTitle"
      :visible.sync="suiteFormVisible"
      :modal-append-to-body="false"
      @closeDialog="closeDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="1000px"
    >
      <el-form :model="formData" class="form-inline">
        <el-form-item>
          <el-input
            clearable
            v-model="formData.name"
            placeholder="名称尽量保持其唯一性，方便识别"
            size="small"
          >
            <template slot="prepend">套件名称</template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            clearable
            v-model="formData.desc"
            placeholder="请输入用例描述信息"
            size="small"
          >
            <template slot="prepend">套件描述</template>
          </el-input>
        </el-form-item>
      </el-form>

      <el-form :inline="true" :model="formData" class="form-inline">
        <el-form-item label="用例名称">
          <el-input
            clearable
            v-model="caseName"
            placeholder="请输入用例名称"
            size="small"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadCase" size="small"
            >查询</el-button
          >
        </el-form-item>
      </el-form>

      <!-- <div>
        <el-transfer
          filterable
          :filter-method="filterMethod"
          filter-placeholder="请输入城市拼音"
          v-model="transferValue"
          :data="data"
        >
        </el-transfer>
      </div> -->

      <!-- // 拖拽列表 -->
      <div style="display: flex;">
        <draggable
          :scroll="true"
          class="left-suite"
          :list="caseData"
          :group="{ name: 'people', pull: 'clone', put: false }"
          style="height:400px"
        >
          <div
            class="list-group-item"
            v-for="(element, index) in caseData"
            :key="index"
            style="cursor: pointer; margin-top: 5px; overflow: auto;"
          >
            <div class="suite_edit">
              <span class="block-summary-description">{{ element.name }}</span>
            </div>
          </div>
        </draggable>
        <br />

        <draggable
          class="right-suite"
          :list="caseList"
          group="people"
          style="height:400px"
        >
          <div
            class="list-group-item"
            v-for="(element, index) in caseList"
            :key="`${element.name}${index}`"
            style="cursor: pointer; margin-top: 5px; overflow: auto;display: flex"
          >
            <div class="edit__block--right">
              <span class="block-summary-description">{{ element.name }}</span>
            </div>
            <div>
              <i
                class="el-icon-delete delete"
                @click="deleteComponents(index, element)"
              ></i>
            </div>
          </div>
        </draggable>
      </div>

      <div style="text-align: left">
        <el-pagination
          background
          :page-size="casePagination.pageSize"
          layout="total, prev, pager, next"
          :total="casePagination.total"
          :current-page.sync="casePagination.page"
          @current-change="loadCase(casePagination.page)"
          style="margin-bottom: 0px; padding-bottom: 0px"
        >
        </el-pagination>
      </div>

      <!-- // 按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="suiteFormVisible = false" size="small"
          >取 消
        </el-button>
        <el-button type="primary" @click="submitForm" size="small"
          >确 定
        </el-button>
      </div>
    </el-dialog>

    <!-- // 运行接口结果弹窗 -->
    <el-dialog
      :visible.sync="reportVisible"
      :modal-append-to-body="false"
      width="1500px"
      center
      :close-on-click-modal="false"
    >
      <report :result="result"></report>

      <div slot="footer" class="copy-footer">
        <el-button type="primary" @click="handleCencelReport" size="small"
          >确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { queryCase } from "@/api/case";
import { addSuite, deleteSuite, querySuite, updateSuite } from "@/api/suite";
import draggable from "vuedraggable";
import moment from "moment";
import { runSuit } from "@/api/run";
import Report from "@/views/interface/components/report";

export default {
  name: "",
  props: {},
  components: {
    draggable,
    Report
  },
  computed: {},
  watch: {},
  created() {
    this.loadSuite();
  },
  mounted() {},
  data() {
    // const generateData = _ => {
    //   const data = [];
    //   const cities = ["上海", "北京", "广州", "深圳", "南京", "西安", "成都"];
    //   const pinyin = [
    //     "shanghai",
    //     "beijing",
    //     "guangzhou",
    //     "shenzhen",
    //     "nanjing",
    //     "xian",
    //     "chengdu"
    //   ];
    //   cities.forEach((city, index) => {
    //     data.push({
    //       key: index,
    //       label: city,
    //       pinyin: pinyin[index]
    //     });
    //   });
    //   return data;
    // };
    return {
      // data: generateData(),
      // transferValue: [],
      // filterMethod(query, item) {
      //   return item.pinyin.indexOf(query) > -1;
      // },

      // runMode: [
      //   { lable: "同时运行", value: 0 },
      //   { lable: "异步运行", value: 1 }
      // ],

      project_id: parseInt(window.localStorage.getItem("projectId")),

      // 【运行接口结果弹窗】
      reportVisible: false,
      isAdd: "",
      dialogTitle: "",

      // 查询表单
      queryForm: {
        name: undefined,
        mode: undefined
      },

      // 套件表单
      suiteFormVisible: false,
      formData: {
        name: undefined,
        desc: undefined,
        case_list: undefined,
        project_id: parseInt(window.localStorage.getItem("projectId"))
      },

      // 【主体表格数据】
      tableData: [],
      // 分页属性
      pagination: {
        total: 0,
        page: 1,
        pageSize: 12
      },

      reportResult: {},

      result: {
        0: "失败",
        1: "通过",
        9: "未知"
      },

      // 【用例分页】
      casePagination: {
        total: 0,
        page: 1,
        pageSize: 11
      },
      caseData: [],
      caseList: [],
      caseName: ""
    };
  },
  methods: {
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.loadSuite();
    },

    loadSuite() {
      querySuite({
        page: this.pagination.page,
        page_size: this.pagination.pageSize,
        project_id: parseInt(window.localStorage.getItem("projectId")),
        name: this.queryForm.name
      })
        .then(res => {
          this.tableData = res.data.result;
          this.pagination.total = res.data.total;
        })
        .catch(err => {
          console.log("错误消息：", err);
        });
    },

    // 查询测试用例
    loadCase() {
      queryCase({
        page: this.casePagination.page,
        page_size: this.casePagination.pageSize,
        name: this.caseName,
        project_id: parseInt(window.localStorage.getItem("projectId"))
      })
        .then(res => {
          this.caseData = res.data.result;
          this.casePagination.total = res.data.total;
        })
        .catch(err => {
          console.log("错误消息：", err);
        });
    },

    deleteComponents(index, item) {
      this.caseList.splice(index, 1);
    },

    // 关闭弹窗
    closeDialog() {
      this.$refs["formInfo"].resetFields();
    },

    //运行测试套件
    runSuit(index, row) {
      runSuit({
        project_id: row.project_id,
        id: row.id
      })
        .then(res => {
          let data = res.data.result;
          if (res.data.code == 200) {
            this.result = data;
            this.result.status = data.success;
            this.result.interfaceName = data.details[0].name;
            this.reportVisible = true;
            this.loadSuite(this.pagination.page);
          } else {
            this.$message.error("运行错误: " + res.data.msg);
          }
        })
        .catch(err => {
          console.log("错误信息：" + err);
        });
    },

    // 新增套件
    handleAddSuite() {
      this.loadCase();
      this.dialogTitle = "新增套件";
      this.isAdd = true;
      this.suiteFormVisible = true;
      this.formData.id = undefined;
      this.formData.name = undefined;
      this.formData.desc = undefined;
      this.formData.case_list = [];
      this.caseList = [];
    },

    // 编辑按钮
    editData(index, row) {
      this.loadCase();
      this.dialogTitle = "编辑套件";
      this.isAdd = false;
      this.suiteFormVisible = true;
      this.formData.id = row.id;
      this.formData.name = row.name;
      this.formData.desc = row.desc;
      this.caseList = row.case_list;
    },

    // 新增事件
    addSuite() {
      addSuite(this.formData)
        .then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: "success",
              message: "新增成功"
            });
            this.suiteFormVisible = false;
            this.loadSuite();
          } else {
            this.$message.error("新增失败: " + res.data.msg);
          }
        })
        .catch(err => {
          this.$message.error("新增失败: " + err);
        });
    },

    // 编辑事件
    handleEdit() {
      updateSuite(this.formData)
        .then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: "success",
              message: "编辑成功"
            });
            this.suiteFormVisible = false;
            this.loadSuite();
          } else {
            this.$message.error("编辑失败: " + res.data.msg);
          }
        })
        .catch(err => {
          this.$message.error("编辑失败: " + err);
        });
    },

    // 新增/编辑确定按钮事件
    submitForm() {
      const list = [];
      this.caseList.forEach(function(item) {
        list.push(item.id);
      });
      this.formData.case_list = list;
      if (!this.isAdd) {
        this.handleEdit();
      } else {
        this.addSuite();
      }
    },

    // 删除套件
    handleDelete(id) {
      {
        this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            deleteSuite({ id }).then(res => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.loadSuite();
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      }
    },

    handleCencelReport() {
      this.reportVisible = false;
      this.loadInterface();
    },

    // 编写日期格式化方法
    dateFormat: function(row, column) {
      const date = row[column.property];
      if (date === undefined) {
        return "";
      }
      // 这里的格式根据需求修改
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    }
  }
};
</script>

<style lang="less">
.suite_edit {
  padding: 5px 0 5px 10px;
  background-color: #eaf1ff;
}

.edit__block--right {
  padding: 5px 0 5px 10px;
  //border: 1px solid #838782;
  width: 95%;
  background-color: #eaf1ff;
}

.left-suite {
  height: 500px;
  border: 0.5px solid #838782;
  width: 50%;
  padding: 5px;
}

.right-suite {
  height: 500px;
  overflow-y: auto;
  border: 0.5px solid #838782;
  width: 50%;
  padding: 5px;
}

.block-summary-description {
  word-break: normal;
  width: auto;
  display: block;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow: hidden;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  font-family: Open Sans, sans-serif;
  color: #3b4151;
}
</style>
